package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author 马迎迎
 * @Title: LoginController
 * @Package com.atguigu.gulimall.ssoserver.controller
 * @Description: TODO(添加描述)
 * @date 2021年05月27日 15:58
 */
@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;
    @ResponseBody
    @GetMapping("/useInfo")
    private String userInfo(@RequestParam("token")String token){
        String s = redisTemplate.opsForValue().get(token);
        return s;
    }
    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("url") String url,
                          HttpServletResponse servletResponse){
        if(!StringUtils.isEmpty(username)&&!StringUtils.isEmpty(password)){
            //登录成功 跳转到之前的页面
            //把登录成功的用户存起来
            String uuid = UUID.randomUUID().toString().replace("-","");
            redisTemplate.opsForValue().set(uuid,username);
            Cookie ssoToken = new Cookie("ssoToken",uuid);
            servletResponse.addCookie(ssoToken);
            return "redirect:"+url+"?token="+uuid;
        }
        //登录失败，展示登录页
        return "login";
    }

    @GetMapping("/login.html")
    public String loginPage(@RequestParam(value = "redirect_url") String url, Model model,
                            @CookieValue(value = "ssoToken",required = false)String ssoToken){
        if(!StringUtils.isEmpty(ssoToken)){
            //以前在认证中心登录过，给浏览器留下了痕迹
            return "redirect:"+url+"?token="+ssoToken;
        }else {
            //在该浏览器第一次登录，没有留下过cookie痕迹
            model.addAttribute("url",url);
            return "login";
        }

    }
}
